<?php
namespace app\admin\controller;

/*
 *	系统安装程序
 * 
 */

use think\{Controller,Request,Db,Cache};
use \app\admin\model\Syslog;
use \app\base\Backup;

class Install extends Controller
{
    public function _initialize()
    {
    	//执行父类的构造方法
    	parent::_initialize();
    }
	//安装程序首页
    public function index()
    {
		$install_flag=ROOT_PATH .'application'.DS.'data'. DS .'database/install';
		$flag=@file_get_contents($install_flag);
		if($flag=='AlreadyInstalled'){
			J(url('index/index'),'FastPHP系统已经安装过了！');
		}
		$request=Request::instance();
		$this->assign('BindRoot','/admin.php/');
		$this->assign('Controller',strtolower($request->controller()));
		$this->assign('Method',strtolower($request->action()));
		return $this->fetch();
    }
	//重新安装
	public function reinstall()
	{
		$install_flag=ROOT_PATH .'application'.DS.'data'. DS .'database/install';
		\unlink($install_flag);
		J(url('install/index'));
	}
	//立即处理安装程序
	public function install_do()
	{
		$data=Request::instance()->post();
		
		$hostname 			=$data['hostname']; 
		$username 			= $data['username']; 
		$password 			= $data['password']; 
		$database 			= $data['database'];
		$adminpassword 		= $data['adminpassword'];
		
		//获得默认数据库配置
		$config = config('database');
		
		$mysql_conn=@mysqli_connect($hostname,$username,$password);
		if(!$mysql_conn){
			ShowJson(1,'数据库连接失败，请认真检查数据库服务器地址/用户名/密码是否正确！');
		}
		if(mysqli_select_db($mysql_conn,$database)){
			//删除所有的数据表
			$res=mysqli_query($mysql_conn,'SHOW TABLES');
			while($row=mysqli_fetch_array($res)){
				$table=$row[0];
				mysqli_query($mysql_conn,"DROP TABLES `$table`");
			}
		}else{
			if(!mysqli_query($mysql_conn,"CREATE database ".$database." DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci")){
				ShowJson(1,'数据库创建失败,请确认账号是否有权限!');
			}	
		}
		
		//生成数据库配置文件
		$config_temp=$this->get_config_temp();
        $config_file = ROOT_PATH . DS . 'application' . DS . 'database.php';
        $config_temp = str_replace("#hostname#", $hostname, $config_temp);
        $config_temp = str_replace("#database#", $database, $config_temp);
        $config_temp = str_replace("#username#", $username, $config_temp);
        $config_temp = str_replace("#password#", $password, $config_temp);
        file_put_contents($config_file, $config_temp);
		
		$config['hostname']=$hostname;
		$config['database']=$database;
		$config['username']=$username;
		$config['password']=$password;
		
		$backup = new Backup($config);
		
		$info = $backup->restore('base.bak');
		
		//初始化Admin管理员密码
        $safecode=GetRandStr(16);
		$admin_pass=Encrypt($safecode,$adminpassword);
		mysqli_select_db($mysql_conn,$database);
		mysqli_query($mysql_conn,"UPDATE `php_admin` SET `safecode`='".$safecode."',`password`='".$admin_pass."' WHERE `username`='admin'");
		
		$install_flag=ROOT_PATH .'application'.DS.'data'. DS .'database/install';
		file_put_contents($install_flag,'AlreadyInstalled');
		ShowJson(0,'安装成功');
	}
	//安装数据库生成成功
	public function create_install_db()
	{
		set_time_limit(0);
		
		$install_flag=ROOT_PATH .'application'.DS.'data'. DS .'database'.DS.'install';
		//获得默认数据库配置
		$config = config('database');
		$config["sqlbakname"]='base.bak';
		$backup = new Backup($config);
		$info = $backup->backup();
		@unlink($install_flag);
		
		//创建安装包ZIP包
		$zip = new \ZipArchive();
		$zipfilename=$config['database']."-FastPHP-".time().".zip";
		
		//参数1:zip保存路径，参数2：ZIPARCHIVE::CREATE没有即是创建  
		if(!$zip->open('..'.DS.$zipfilename,\ZIPARCHIVE::CREATE)){
			ShowJson(1,"安装包[".$zipfilename."]生成失败<br/>");
		}
		$this->CreateZip(opendir(ROOT_PATH),$zip,ROOT_PATH);
		$zip->close();
		
		ShowJson(0,'安装包生成成功');
	}
	//创建压缩包
	public function CreateZip($openFile,$zipObj,$sourceAbso,$newRelat = ''){
		while(($file = readdir($openFile)) != false)  
		{  
			if($file=="." || $file=="..")  
				continue;  
			  
			/*源目录路径(绝对路径)*/  
			$sourceTemp = $sourceAbso.DS.$file;  
			/*目标目录路径(相对路径)*/  
			$newTemp = $newRelat==''?$file:$newRelat.DS.$file;  
			if(is_dir($sourceTemp))  
			{  
				$zipObj->addEmptyDir($newTemp);/*这里注意：php只需传递一个文件夹名称路径即可*/  
				$this->CreateZip(opendir($sourceTemp),$zipObj,$sourceTemp,$newTemp);  
			}  
			if(is_file($sourceTemp))  
			{  
				$zipObj->addFile($sourceTemp,$newTemp);  
			}  
		}
	}
	//清理缓存日志
	public function clear_cache_log_dir()
	{
		$cache_dir=ROOT_PATH.DS.'runtime'.DS.'cache';
		$config_dir=ROOT_PATH.DS.'runtime'.DS.'config';
		$developer_log_dir=ROOT_PATH.DS.'runtime'.DS.'developer_log';
		$doc_dir=ROOT_PATH.DS.'runtime'.DS.'doc';
		$log_dir=ROOT_PATH.DS.'runtime'.DS.'log';
		$order_dir=ROOT_PATH.DS.'runtime'.DS.'order';
		$session_dir=ROOT_PATH.DS.'runtime'.DS.'session';
		$temp_dir=ROOT_PATH.DS.'runtime'.DS.'temp';
		$temp_xls_dir=ROOT_PATH.DS.'runtime'.DS.'temp_xls';
		
		DelFile($cache_dir,false);
		DelFile($config_dir,false);
		DelFile($developer_log_dir,false);
		DelFile($log_dir,false);
		DelFile($order_dir,false);
		DelFile($session_dir,false);
		DelFile($temp_dir,false);
		DelFile($temp_xls_dir,false);
		
		ShowJson(0,'清理成功!');
		
	}
	private function get_config_temp(){
		return "<?php
return [
    // 数据库类型
    'type'           => 'mysql',
    // 服务器地址
    'hostname'       => '#hostname#',
    // 数据库名
    'database'       => '#database#',
    // 用户名
    'username'       => '#username#',
    // 密码
    'password'       => '#password#',
    // 端口
    'hostport'       => '',
    // 连接dsn
    'dsn'            => '',
    // 数据库连接参数
    'params'         => [],
    // 数据库编码默认采用utf8
    'charset'        => 'utf8',
    // 数据库表前缀
    'prefix'         => 'php_',
    // 数据库调试模式
    'debug'          => true,
    // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
    'deploy'         => 0,
    // 数据库读写是否分离 主从式有效
    'rw_separate'    => false,
    // 读写分离后 主服务器数量
    'master_num'     => 1,
    // 指定从服务器序号
    'slave_no'       => '',
    // 是否严格检查字段是否存在
    'fields_strict'  => true,
    // 数据集返回类型 array 数组 collection Collection对象
    'resultset_type' => 'array',
    // 是否自动写入时间戳字段
    'auto_timestamp' => false,
    // 是否需要进行SQL性能分析
    'sql_explain'    => false,
];";
	}
}
